package com.ojoin.trade.common.web.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ojoin.trade.common.web.dao.SysAreaDao;
import com.ojoin.trade.common.web.dao.BaseDao;
import com.ojoin.trade.common.web.domain.Area;
import com.ojoin.trade.common.web.service.SysAreaService;
@Service
public class SysAreaServiceImpl extends BaseServiceImpl<Area> implements SysAreaService {

	@Autowired
	private SysAreaDao dao;
	
	@Override
	protected BaseDao<Area> getBaseDao() {
		return dao;
	}

	@Override
	public int delete(Area query) {
		SysManageServiceImpl.removeCache(SysManageServiceImpl.CACHE_AREA_LIST);
		return getBaseDao().delete(query);
	}
	
	
	public void insertTree(Area entity) {
		// 如果没有设置父节点，则代表为跟节点，有则获取父节点实体
		if (entity.getParent() == null || null==entity.getParentId() 
				|| "0".equals(entity.getParentId())){
			entity.setParent(null);
		}else{
			entity.setParent(dao.selectById(Integer.valueOf(entity.getParentId())));
		}
		if (entity.getParent() == null){
			 
			entity.setParent(new Area(0));
			entity.getParent().setParentIds("");
		}
		
		// 获取修改前的parentIds，用于更新子节点的parentIds
		String oldParentIds = entity.getParentIds(); 
		
		// 设置新的父节点串
		entity.setParentIds(entity.getParent().getParentIds()+entity.getParent().getId()+",");
		
		// 保存或更新实体
		if (entity.getIsNewRecord()){
			entity.preInsert();
			dao.insert(entity);
		}else{
			entity.preUpdate();
			dao.updateById(entity);
		}
		
		
		// 更新子节点 parentIds
		Area o = new Area();
		o.setParentIds("%,"+entity.getId()+",%");
		List<Area> list = dao.findByParentIdsLike(o);
		for (Area e : list){
			if (e.getParentIds() != null && oldParentIds != null){
				e.setParentIds(e.getParentIds().replace(oldParentIds, entity.getParentIds()));
				dao.updateParentIds(e);
			}
		}
		
		SysManageServiceImpl.removeCache(SysManageServiceImpl.CACHE_AREA_LIST);
	}
}
